<template>
  <div class="flex h-full">
    <div class="flex flex-col flex-1 overflow-hidden">
      <SearchContainer search-text="搜索" @search="getTableData" @reset="onReset">
        <div class="flex justify-between">
          <a-form ref="formRef" class="form-style-flex" :model="searchData" :label-col="{ style: { width: '80px' } }">
            <a-form-item label="" name="brName" class="w-80">
              <SelectTable
                v-model:value="searchData.brName"
                :search-params="{ stdate: searchData['dateRange']?.[0], eddate: searchData['dateRange']?.[1], lb: 1, xmlbs: [30], fflb: '1' }"
                type="门诊退药患者列表"
                :disabled="!drugStoreId"
                placeholder="姓名/助记码/卡号/手机号/身份证号"
                @select="onSelectPatient"
              />
            </a-form-item>
            <a-form-item label="收费日期" name="dateRange">
              <a-range-picker v-model:value="searchData['dateRange']" class="w-64" format="YYYY-MM-DD" value-format="YYYY-MM-DD" :allow-clear="false" />
            </a-form-item>
          </a-form>
          <a-form class="flex">
            <!-- <SelectDrugRoom
              v-model:value="drugStoreId"
              placeholder="选择药房"
              is-department="1"
              :params="{ isProducer: '1', storetype: '3' }"
              class="w-64 mb-2 mr-4"
              @select="onSelectDrugRoom"
            />-->
            <a-form-item class="w-64" label="审核人">
              <a-select v-model:value="reviewer" :options="pharmacistSelectData" placeholder="请选择" @change="setLocalStorageEvent" />
            </a-form-item>
          </a-form>
        </div>
      </SearchContainer>
      <PatientInfoHeader class="my-2" :patient-info="patientInfo" :show-insurance="true" @change="onReset()">
        <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
        <div>
          <div class="flex items-center">
            <LabelValue class="ml-4" label="卡号" :width="140" :value="patientInfo?.brId" />
            <LabelValue class="ml-4" label="科室" :width="140" :value="patientInfo?.ksmc" />
            <LabelValue class="ml-4" label="类别" :width="140" :value="patientInfo?.ghlb" />
            <!-- <LabelValue class="ml-4" label="过敏史" :width="280" :tooltip="true" :value="patientInfo?.brGms" /> -->
            <AllergyHistory class="ml-4" :width="280" :value="patientInfo.brGms" :patient-info="patientInfo" @success="(e) => (patientInfo.brGms = e)" />
          </div>
          <div class="flex items-center">
            <LabelValue class="ml-4" label="门诊号" :width="140" :value="patientInfo?.jzbh" />
            <LabelValue class="ml-4" label="医生" :width="140" :value="patientInfo?.empName" />
            <LabelValue class="ml-4" label="时间" :width="140" :value="patientInfo?.sfsj" />
            <!-- <LabelValue class="ml-4" label="初步诊断" :width="320" :value="patientInfo?.zdmc" /> -->
          </div>
        </div>
      </PatientInfoHeader>
      <a-card class="w-full flex-1">
        <BaseTable :loading="loading" column-code="000549" :data-source="tableData" row-key="id" fill :pagination="false">
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'mc'">
              <MedicineInfo :value="{ mc: record.mc, gg: record.gg, cj: record.cj }" />
            </template>
            <template v-if="column.dataIndex === 'sl'"> {{ record.sl }}{{ record.dw }} </template>
            <template v-if="column.dataIndex === 'action'">
              <a-button type="link" size="small" @click="openReturnModal(record)"> 退回 </a-button>
            </template>
          </template>
        </BaseTable>
      </a-card>
    </div>
    <ReturnModal v-model:open="returnModalOpen" :row-data="rowData" :reviewer="reviewer" @success="returnSuccess" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import PatientInfoHeader from '@/components/business/PatientInfoHeader'
import { post } from '@/utils/request'
import { judgeDrugStoreStatus, isHave } from '@/utils/tools'
import useUserStore from '@/store/user'
import ReturnModal from './ReturnModal.vue'

const { empId } = useUserStore()

const prescriptionCount = ref({})
const formRef = ref(null)
// const formState = ref({})
const pharmacistSelectData = ref([])
const reviewer = ref(undefined) //审核人
const drugStoreId = ref(undefined) //发药药房
const searchData = ref({
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
})
const patientId = ref('') //就诊编号
const patientInfo = ref({})
const returnModalOpen = ref(false)
const rowData = ref({})

const getTableData = () => {
  patientId.value && getData()
}

//获取门诊患者信息
const getOutpatientInfo = async () => {
  const { data, code } = await post('/outp/mzys/getOutpRecordInfo', { mzjlbh: patientId.value })
  if (code === 0) {
    patientInfo.value = data
    searchData.value.brName = data.brName
  }
}

//获取
const { loading, tableData, getData } = useTable({
  url: '/outp/mzyf/getOutpClinicalOrderInfoMaterialList',
  pagination: false,
  immediate: false,
  formatParams: () => {
    return {
      jzbh: patientId.value,
      // drugStoreId: drugStoreId.value,
      status: 2,
      tclb: '2',
      sfyzfyz: 1
    }
  }
})
const openReturnModal = (record) => {
  if (!reviewer.value) {
    message.error('请选择审核人')
    return
  }
  rowData.value = record
  returnModalOpen.value = true
}

//获取审核人下拉（类别为药剂师）
const getSelectPharmacist = async () => {
  const { code, data } = await post('/operation/opex/getEmpInfoList', {
    emplbid: '5',
    yxzt: 0,
    pageNum: 1,
    pageSize: 9999,
    notEmpIdList: [empId] // 当前登录但id
  })
  if (code !== 0) return
  pharmacistSelectData.value = data.map((item) => {
    return {
      label: item.empName,
      value: item.empId
    }
  })
  const reviewerValue = JSON.parse(window.localStorage.getItem('grantReviewer'))
  if (reviewerValue && reviewerValue.time && reviewerValue.value) {
    //保存24小时
    if (dayjs(dayjs().format()).diff(reviewerValue.time, 'hour') >= 0 && dayjs(dayjs().format()).diff(reviewerValue.time, 'hour') < 24) {
      if (isHave(pharmacistSelectData.value, reviewerValue.value)) reviewer.value = reviewerValue.value
    } else {
      reviewer.value = undefined
    }
  }
}
// const onSelectDrugRoom = (val) => {
//   drugStoreId.value = val.id
//   window.localStorage.setItem(
//     'dispensingMaterialDrugStoreId',
//     JSON.stringify({
//       value: drugStoreId.value
//     })
//   )
// }
const setLocalStorageEvent = () => {
  window.localStorage.setItem(
    'grantReviewer',
    JSON.stringify({
      time: dayjs().format(),
      value: reviewer.value
    })
  )
}
const returnSuccess = () => {
  onReset()
}
const onSelectPatient = (row) => {
  patientId.value = row.jzbh
  searchData.value.brName = row.brName
  // getTableData()
  getData()
  getOutpatientInfo()
}

const onReset = () => {
  formRef.value.resetFields()
  tableData.value = []
  patientInfo.value = {}
  patientId.value = ''
  prescriptionCount.value = {}
}

onMounted(async () => {
  getSelectPharmacist()
  const drugStoreIdValue = JSON.parse(window.localStorage.getItem('dispensingMaterialDrugStoreId'))
  drugStoreId.value = await judgeDrugStoreStatus(drugStoreIdValue?.value, '1', '3')
})
</script>

<style lang="less" scoped>
:deep(.ant-table-row-expand-icon) {
  display: none;
}
</style>
